<?php

namespace app\admin\controller;

use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords as Income;
use app\api\model\Privatechat;
use app\api\model\ConfigSystem;
use think\Db;
use think\Request;
use think\Session;
use Vectorface\Whip\Whip;

class CustomerService extends Common
{
    public function topupPrev()
    {
        $user_id = input('user_id');
        $user_id = intval($user_id);
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if (!$user_id) {
                return ['err' => '用户不存在' . $user_id];
            }
            
            $user = Db::name('user')->find($user_id);
            
            if (!$user) {
                return ['err' => '用户不存在'];
            }
            if (!$user['yqr']) {
                return ['err' => '尚未绑定上级'];
            }
            $parent = Db::name('user')->where(['yqm' => $user['yqr']])->find();
            if (!$parent) {
                return ['err' => '上级用户不存在'];
            }
            
            /*if ($post['channel'] == 1) {
                Balance::index($user_id, $post['price'], $post['content'], $post['toward']);
            } else {
                $toward = $post['toward'] ? 0 : 1;
                Income::index($user_id, 0, $post['price'], $post['content'], 1, '', $toward);
            }*/
            
            if ($user['invite_time']) {
                $topup_total = Db::name('topup')->where(['fk_userid' => $user_id, 'type' => ['in', [0, 1]], 'state' => 1, 'addtime' => ['lt', date('Y-m-d H:i:s', $user['invite_time'])]])->sum('price');
            } else {
                $topup_total = 0;
            }
            
            $current_time = time();
            
            $admin = session('admin', '', 'mmjtAdmin');
            if ($post['money'] > 20000) {
                return ['err' => '金额填写不得超过 20000'];
            }
            $config = ConfigSystem::index('invite');
            $money = $post['money'] * 5 * 0.18;
            if ($config['shouyi_limit_switch'] && strtotime($config['shouyi_limit_time']) <= strtotime($user['register_datetime'])) {
                $money = $post['money'] * 5 * $config['shouyi_1_max'];
            } 
            $send_topup_total = $post['money'];
            Db::name('customer_service_topup')->insert([
                'admin_id' => $admin['id'],
                'parent_id' => $parent['id'],
                'user_id' => $user_id,
                'channel' => $post['channel'],
                'toward' => $post['toward'],
                'money' => $money,
                'ip' => (new Whip())->getValidIpAddress(),
                'os' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                'data' => json_encode(['invite_time' => $user['invite_time'], 'topup_total' => $topup_total, 'send_topup_total'=>$send_topup_total]),
                'create_time' => $current_time,
                'update_time' => $current_time
            ]);
            
            $data = ['ret' => '成功'];
            
        } else {
            if ($user_id) {
                $user = Db::name('user')->find($user_id);

                if (!$user) {
                    $this->error('用户不存在');
                }
                if (!$user['yqr']) {
                    $this->error('尚未绑定上级');
                }
                
                $parent = Db::name('user')->where(['yqm' => $user['yqr']])->find();
                if (!$parent) {
                    $this->error('上级用户不存在');
                }
                
                $user['invite_user_id'] = $parent['id'];
                $user['invite_user_name'] = $parent['name'];
                $user['invite_user_score'] = $parent['score'];
                
                $this->assign('name', $user);
                $data = $this->fetch();
            } else {
                $this->error('参数错误');
            }
        }
        return $data;
    }
    
    public function topupPrevRecords()
    {
        $where = ['channel' => 2, 'toward' => 1];
        
        $status = input('status');
        if ($status !== null) {
            $where['status'] = $status;
        }
        
        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if (in_array($search_type, ['user_id', 'parent_id'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }
        
        $data = Db::name('customer_service_topup')->master()->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item, $key) {
            $item['data'] = json_decode($item['data'], true);
            $item['count'] = Db::name('customer_service_topup')->where(['user_id'=>$item['user_id'],'status'=>1])->count();
            return $item;
        });
        
        $data_array = $data->toArray()['data'];
        
        $uids = [];
        foreach ($data_array as $item) {
            if ($item['user_id']) {
                $uids[] = $item['user_id'];
            }
            if ($item['parent_id']) {
                $uids[] = $item['parent_id'];
            }
        }
        $uids = array_unique($uids);
        $users = Db::name('user')->where(['id' => ['in', $uids]])->column('id, name, register_datetime', 'id');
        
        $this->assign('users', $users);
        
        $this->assign('status', $status);
        
        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);
        
        return $this->fetch();
    }
    
    public function topupPrevAdd()
    {
        $id = input('id');
        
        if (request()->isAjax()) {
            
            $post = input('post.');
            
            if ($id) {
                $records = Db::name('customer_service_topup')->where(['id' => $id, 'channel' => 2, 'toward' => 1, 'status' => 0])->find();
                if (!$records) return ['err' => '记录不存在'];
                
                $db = Db::name('customer_service_topup')->where('id', $id)->update(['status' => $post['status'], 'update_time' => time()]);
                if ($post['status'] == 1) {
                    $user = Db::name('user')->find($records['user_id']);
                    $parent = Db::name('user')->find($records['parent_id']);
                    if ($user && $parent) {
                        $data = json_decode($records['data'], true);
                        
                        Income::index($records['parent_id'], $records['user_id'], $records['money'], $user['name'] . '(' . $records['user_id'] . ') 绑定奖励补发', 1);
    
                        $content = "绑定之前，下级:" . $user['name'] . "(" . $records['user_id'] . ") 充值" . $data['send_topup_total'] . "元，给你补奖励" . $records['money'] . "。";
                        
                        Privatechat::notice($records['parent_id'], $content);
                    }
                }
                
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }

    public function topupPrevDel()
    {
        if (request()->isAjax()) {
            $pid = input('id');
            if ($pid) {
                $res = Db::name('customer_service_topup')->delete($pid);
                if ($res) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }



    public function page()
    {
        $where = ['sys_channel'=>['in', [0,getenv('APP_CHANNEL')]]];
        
        $search = input('param.name');
        if ($search) {
            $where['title|body'] = ['like', '%' . $search . '%'];
        }

        $data = Db::name('page_kefu')->where($where)->order('update_time desc, id asc')->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function addpage()
    {
        $id = input("id");
        if (request()->isAjax()) {
            $post = input('post.');
            $post['body'] = Request::instance()->post('body','','htmlspecialchars');

            if (!isset($post['body']) || !$post['body']) {
                return ['err' => '内容不能为空'];
            }

            $post['sys_channel'] = getenv('APP_CHANNEL');
            $post['body'] = in_content($post['body']);

            if (!$id) {   // 添加数据
                $post['create_time'] = time();
                $db = Db::name('page_kefu')->insert($post);
                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {      //修改数据
                if ($post['id'] != $id) {
                    $has = Db::name('page_kefu')->find($post['id']);
                    if ($has) return ['err'=>'ID 已存在'];
                }
                $post['update_time'] = time();
                $db = Db::name('page_kefu')->where('id', $id)->update($post);
                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('page_kefu')->where('id', $id)->find();
                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }
        return $data;
    }
    public function pageview()
    {
        $admin = Session::get('admin', 'mmjtAdmin');
        $id = input('id/d');

        $data = Db::name('page_kefu')->cache(true)->find($id);

        preg_match_all("/{(.*?)}/", $data['body'], $content);

        $content[1] = array_unique($content[1]);

        foreach ($content[1] as $item) {
            $data['body'] = str_replace('{'.$item.'}', getenv($item), $data['body']);
        }

        Db::name('page_kefu_records')->insert(['pid'=>$id, 'admin_id'=>$admin['id'], 'time'=>time()]);

        $this->assign('data', $data);
        return $this->fetch();
    }

    public function pagedel()
    {
        $id = input("id");
        $db = Db::name('page_kefu')->delete($id);
        if ($db) {
            $data = ['ret' => '删除成功'];
        } else {
            $data = ['err' => '删除失败'];
        }

        return $data;
    }

    public function pagerecords()
    {
        $where = [];
        $search = input('param.name');
        $search_type = input('param.type');
        if ($search) {
            $where[$search_type] = $search;
        }
        $admins = Db::name('admin')->column('name','id');
        $pages = Db::name('page_kefu')->column('title','id');

        $data = Db::name('page_kefu_records')->where($where)->order('time desc, id asc')->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item) use ($admins, $pages) {
            $item['title'] = $pages[$item['pid']];
            $item['admin'] = $admins[$item['admin_id']];
            return $item;
        });
        
        $page = $data->render();
        $this->assign('page', $page);
        
        $this->assign('data', $data);
        return $this->fetch();
    }
}
